import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
#设定数值完整打印
pd.set_option('display.max_columns', None) 
pd.set_option('display.max_rows', None) 
pd.set_option('max_colwidth',100)

customers=pd.read_csv('input/olist_customers_dataset.csv')
geolocation=pd.read_csv('input/olist_geolocation_dataset.csv')
order_items=pd.read_csv('input/olist_order_items_dataset.csv')
order_payments=pd.read_csv('input/olist_order_payments_dataset.csv')
order_reviews=pd.read_csv('input/olist_order_reviews_dataset.csv')
orders=pd.read_csv('input/olist_orders_dataset.csv')
products=pd.read_csv('input/olist_products_dataset.csv')
sellers=pd.read_csv('input/olist_sellers_dataset.csv')
translation=pd.read_csv('input/product_category_name_translation.csv')
#连接表格,Concatenating DataFrames
order_merge_list=[order_items,order_payments,order_reviews]

for item in order_merge_list:
	orders=pd.merge(orders,item,on='order_id',how='left')

orders=pd.merge(orders,products,on='product_id',how='left')

#完成连接交易信息表格，此处加上了巴西语言对应的英文翻译
orders_full=pd.merge(orders,translation,on='product_category_name',how='left')

#完成连接卖家地理位置表格
sellers_geo=pd.merge(sellers,geolocation,left_on='seller_zip_code_prefix',right_on='geolocation_zip_code_prefix')

#完成连接买家地理位置表格
customers_geo=pd.merge(customers,geolocation,left_on='customer_zip_code_prefix',right_on='geolocation_zip_code_prefix')

#定义时间序列
date_cols=['order_purchase_timestamp','order_approved_at','order_delivered_carrier_date','order_delivered_customer_date' ,'order_estimated_delivery_date','shipping_limit_date','review_creation_date','review_answer_timestamp']
for item in date_cols:
    orders_full[item]=pd.to_datetime(orders_full[item])
# orders_full.info()  

def sale_statistics():
    plt.subplots()
    product_counts=orders_full.groupby(['product_category_name_english']).size().sort_values()
    product_counts.plot(kind='barh',figsize=(10,40),title='Product Category')
    plt.style.use('ggplot')
    plt.show()

def paymement_method():
     #支付手段统计分析
    plt.subplots()
    payment_counts=orders_full["payment_type"][orders_full["payment_type"]!='not_defined'].value_counts()
    explode = [0, 0.1, 0, 0]
    payment_counts.plot(kind="pie",autopct='%1.1f%%', pctdistance=0.6, shadow=True,figsize=(8,8),explode=explode, startangle = 90,labels=None,legend=True)
    plt.title("Paymement methods", fontweight='bold', size=16)
    plt.show()

def payment_instalment():
    plt.subplots()
    #分期付款分布情况
    sns.distplot(orders_full['payment_installments'].dropna(),bins=25)
    plt.show()

def daily_sells():
    Daily_sells=orders_full['order_purchase_timestamp'].value_counts().resample('D').sum()
    Daily_sells.plot(figsize=(15,10),title='Daily sells')
    plt.show()
    
def Months_amount():
    amount=orders_full.loc[:,['order_purchase_timestamp','payment_value']].set_index('order_purchase_timestamp').sort_index()

    Months_amount=amount.resample('M').sum()
    print(Months_amount.max())

    Months_amount.plot(kind='bar',figsize=(15,10),title='Months_amount')
    plt.show()

def Finding_the_most_recommended_seller():
    seller_review=orders_full.loc[:,['seller_id','review_score']]
    score=seller_review.groupby(['seller_id']).mean()
    owns=seller_review['seller_id'].value_counts()
    #设定条件为评价数大于300条
    scores=score[owns>300]
    scores_sorted=scores.loc[:,'review_score'].sort_values()
    #查看前5名
    print(scores_sorted.tail())

    plt.subplots()
    scores_sorted.plot(kind='barh',figsize=(10,40),title='Review Score Ranklist(seller reviews>300)')
    plt.show()

def top_ten_customer():
    Tuhao=orders_full.loc[:,['customer_id','payment_value']].groupby(['customer_id']).sum().sort_values(by='payment_value')
    Tuhao_buy_counts=orders_full['customer_id'].value_counts().sort_values()
    print(Tuhao.tail(10))
    Tuhao.tail(10).plot(kind='barh',title='Top 10 Customers')
    print('\nCustomer 1617b1357756262bfa56ab541c47bc16 ordered '+str(Tuhao_buy_counts['1617b1357756262bfa56ab541c47bc16'])+' times')
    plt.show()

def sellers_city():
    #分组
    seller_cites=sellers_geo.groupby(['seller_id','seller_city']).size().sort_values()
    seller_cites_counts=seller_cites.groupby(['seller_city']).size().sort_values()
    #可视化排名前20的城市
    seller_cites_counts.tail(20).plot(kind='barh',figsize=(10,10),title='Seller cites ')
    plt.show()

def customers_city():
    customer_cites=customers_geo.groupby(['customer_unique_id','customer_city']).size().sort_values()
    customer_cites_counts=customer_cites.groupby(['customer_city']).size().sort_values()
    #可视化排名前20的城市
    customer_cites_counts.tail(20).plot(kind='barh',figsize=(10,10),title='Customer cites ')
    plt.show()
if __name__ == '__main__':
    paymement_method()